//
//  XGTextView.swift
//  Xwg
//
//  Created by Xwg on 2018/8/30.
//  Copyright © 2018年 Xwg. All rights reserved.
//

import Foundation
import UIKit

@IBDesignable
open class XGTextView: UITextView {

    // MARK: - placeholder
    /// placeholder 的内容
    @IBInspectable var placeholder: String? {
        get { return placeholderLabel.text }
        set { placeholderLabel.text = newValue }
    }
    
    /// placeholder 的行数(默认：1)
    @IBInspectable var placeholderNumberOfLines: Int {
        get { return placeholderLabel.numberOfLines }
        set {
            guard newValue >= 0 else { return }
            placeholderLabel.numberOfLines = newValue
        }
    }
    
    /// placeholder 的颜色(默认：UIColor(red: 0, green: 0, blue: 25.0/255.0, alpha: 0.22))
    @IBInspectable var placeholderColor: UIColor {
        get { return placeholderLabel.textColor }
        set { placeholderLabel.textColor = newValue }
    }
    
    /// placeholder 的背景颜色(默认：nil)
    @IBInspectable var placeholderBackgroundColor: UIColor? {
        get { return placeholderLabel.backgroundColor }
        set { placeholderLabel.backgroundColor = newValue }
    }
    
    /// placeholder
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 0, green: 0, blue: 25.0/255.0, alpha: 0.22)
        label.numberOfLines = 0
        return label
    }()
    
    // MARK: - 初始化
    public override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        initSetup()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initSetup()
    }
    public func initSetup() {
        // 设置约束
        addSubview(placeholderLabel)    // 系统默认会给 autoresizing 约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false  // 关闭 autoresizing 不关闭否则程序崩溃
        placeholderLabel.superview!.addConstraints(placeholderLabelContatins())
        
        // 增加通知
        NotificationCenter.default.addObserver(self, selector: #selector(handlePlaceholderIsHidden), name: .UITextViewTextDidChange, object: self)
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        // 处理是否需要
        handlePlaceholderIsHidden()
    }
    
    open override var font: UIFont? {
        didSet { placeholderLabel.font = font }
    }
    
    open override var text: String! {
        didSet { placeholderLabel.isHidden = !text.isEmpty }
    }
    
    deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self, name: .UITextViewTextDidChange, object: self)
    }
}

extension XGTextView {
    private func placeholderLabelContatins() -> [NSLayoutConstraint] {
        let marginY: CGFloat = 8.0
        let marginX: CGFloat = 5.0
        let phWidth = NSLayoutConstraint(item: placeholderLabel,
                                        attribute: .width,
                                        relatedBy: .lessThanOrEqual,
                                        toItem: self,
                                        attribute: .width,
                                        multiplier: 1.0,
                                        constant: -2 * marginX)
        let phHeight = NSLayoutConstraint(item: placeholderLabel,
                                          attribute: .height,
                                          relatedBy: .lessThanOrEqual,
                                          toItem: self,
                                          attribute: .height,
                                          multiplier: 1.0,
                                          constant: -2 * marginY)
        let phTop = NSLayoutConstraint(item: placeholderLabel,
                                       attribute: .top,
                                       relatedBy: .equal,
                                       toItem: self,
                                       attribute: .top,
                                       multiplier: 1.0,
                                       constant: marginY)
        let phLeft = NSLayoutConstraint(item: placeholderLabel,
                                        attribute: .left,
                                        relatedBy: .equal,
                                        toItem: self,
                                        attribute: .left,
                                        multiplier: 1.0,
                                        constant: marginX)
        let phBottom = NSLayoutConstraint(item: placeholderLabel,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: self,
                                          attribute: .bottom,
                                          multiplier: 1.0,
                                          constant: marginY)
        let phRight = NSLayoutConstraint(item: placeholderLabel,
                                         attribute: .right,
                                         relatedBy: .equal,
                                         toItem: self,
                                         attribute: .right,
                                         multiplier: 1.0,
                                         constant: marginX)
        
        return [phWidth, phHeight, phTop, phLeft, phBottom, phRight]
    }
    @objc private func handlePlaceholderIsHidden() {
        placeholderLabel.isHidden = !text.isEmpty
    }
}
